package com.youbenzi.dockerpool;

import java.io.Closeable;
import java.net.MalformedURLException;

import com.caucho.hessian.client.HessianProxyFactory;

public class DockerConnection implements Closeable {

	private	String type;
	private String host;
	private int port;
	private DockerFactory dockerFactory;
	public DockerConnection(String type, String host, DockerFactory factoryInSingleHost) {
		super();
		this.type = type;
		this.host = host;
		
		String portStr = Register.use(type, host);
		if(portStr == null) {
			throw new NotEnableConnectionException();
		}
		this.port = Integer.parseInt(portStr);

		try {
			HessianProxyFactory factory = new HessianProxyFactory();
			dockerFactory = (DockerFactory) factory.create(DockerFactory.class, hessianUrl());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			System.out.println("没有配置Hessian服务，使用单机模式");
			dockerFactory = factoryInSingleHost;
		}
		int num = Register.num(type, host);
		if(num < Config.maxDockerNum) {		//如果已登记连接数（未使用和使用中）小于最大docker 容器数，则创建一个新的docker 镜像待用
			new DockerCreater(type, host, dockerFactory).create();
		}
	}

	@Override
	public void close() {
		
		dockerFactory.removeContainer(type, host, port);
		Register.release(type, host);
		
		int num = Register.num(type, host);
		if(num < Config.minDockerNum) {		//如果已登记连接数（未使用和使用中）小于最小容器数，则创建一个新的docker 镜像待用
			new DockerCreater(type, host, dockerFactory).create();
		}
	}
	
	public String server() {
		return "http://" + getHost() + ":" + getPort();
	}

	private String hessianUrl () {
		return "http://" + Config.server(host) + "/pool";
	}
	
	public String getType() {
		return type;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public DockerFactory getDockerFactory() {
		return dockerFactory;
	}
	
}
